package com.test.mchelepesa.activity_fragment_rice.info_rice;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.ContactsContract;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;

import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseInfoActivity_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessData_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessStep_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.view_rice.ContactInputWigets;
import com.test.mchelepesa.view_rice.base_rice.BaseInfoInputViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.ContactViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.CreditReportViewManager_Niri_rice;
import com.test.mchelepesa.view_rice.info_input_rice.DatePickViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.GenderSelectViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.InputViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.SelectRelationshipViewManager_rice;
import com.test.mchelepesa.view_rice.info_input_rice.SelectViewManager_rice;
import com.test.mchelepesa.view_rice.widget_rice.TitleView_rice;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.TreeMap;

public class InfoUploadActivity_rice extends BaseInfoActivity_rice {

    private LinearLayout groupLayout;
    private TitleView_rice titleView;

    private ArrayList<BaseInfoInputViewManager_rice> infoInputViewManagers = new ArrayList<>();

    private ProcessStep_rice step;

    private String buriedPointFalg = "";
    private String activityFlag = "";

    //尼日银行选择
    private String paramNameBankCode = "";
    private ProcessData_rice bankNameData;
    private final TreeMap<String,String> map_bankName_bankCode = new TreeMap<>();

    private final ArrayList<ContactInputWigets> contactWSList = new ArrayList<>();
    private int selectContact = -1;
    private long startTime = 0;

    private final ActivityResultLauncher<Intent> selectContactArl = registerForActivityResult(new ActivityResultContracts.StartActivityForResult(),
            result -> {
                try {
                    Intent data = result.getData();
                    if (data!=null && result.getResultCode()==RESULT_OK && selectContact>=0 && contactWSList.size()>selectContact){
                        Uri contactUri = data.getData();
                        String[] queryFields = new String[]{
                                ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME,
                                ContactsContract.CommonDataKinds.Phone.NUMBER
                        };
                        Cursor cursor = getContentResolver().query(contactUri,queryFields,null,null,null);
                        if (cursor!=null){
                            if (cursor.moveToFirst()){
                                @SuppressLint("Range") String name = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.DISPLAY_NAME));
                                @SuppressLint("Range") String mobile = cursor.getString(cursor.getColumnIndex(ContactsContract.CommonDataKinds.Phone.NUMBER));
                                final long time2 = System.currentTimeMillis();
                                HttpManager_rice.getInstance().saveUserBuriedPoint(
                                        buriedPointFalg+"_CONTACT_SELECT_"+selectContact+"_INPUT",name+":"+mobile+"$$"+(time2-startTime));
                                contactWSList.get(selectContact).setMobilenAndName(mobile,name);
                            }
                            cursor.close();
                        }
                    }
                }catch (Exception e){
                    StringUtil_rice.printException(e);
                }
            }
    );

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_info_upload_rice);
        init();
    }

    @SuppressLint("InflateParams")
    private void init(){
        titleView = findViewById(R.id.activity_info_upload_view_title);
        setBackBtn_rice(titleView.getBackIb());

        initLicense(
                findViewById(R.id.activity_info_upload_view_license),
                findViewById(R.id.activity_info_upload_license_logo),
                findViewById(R.id.activity_info_upload_license_company_name)
        );

        groupLayout = findViewById(R.id.activity_info_upload_layout_group);

        findViewById(R.id.activity_info_upload_btn_next).setOnClickListener(v -> {

            titleView.requestFocus();

            HttpManager_rice.getInstance().saveUserBuriedPointAndUpload((buriedPointFalg + "_NEXT_CLICK").toUpperCase(),"");

            for (BaseInfoInputViewManager_rice widgetsManager: infoInputViewManagers){
                if (!widgetsManager.checkInput()){
                    showToast_rice(getString(R.string.word_input_tip));
                    return;
                }
            }

            if (step ==null) return;
            String url = step.getApiUrl();
            if (url.isEmpty()) return;
            TreeMap<String,String> dataMap = new TreeMap<>();

            //添加通用信息
            for (BaseInfoInputViewManager_rice baseInfoInputViewManager: infoInputViewManagers){
                ProcessData_rice data = baseInfoInputViewManager.getData();
                if (data==null) continue;
                dataMap.put(data.getParamName(),baseInfoInputViewManager.getInput());
            }

            //添加联系人信息
            if (!contactWSList.isEmpty()&&!TextUtils.isEmpty(step.getContactParamName())){
                JSONArray jsonArray = new JSONArray();
                for (ContactInputWigets contactWS:contactWSList){
                    jsonArray.put(contactWS.toJson());
                }
                dataMap.put(step.getContactParamName(),jsonArray.toString());
            }

            HttpManager_rice.getInstance().uploadInfo(url,dataMap);
        });

        View tipsView = findViewById(R.id.activity_info_upload_view_tips);
        TextView tipsTv = findViewById(R.id.activity_info_upload_tv_tips);


        step = ProcessInfo_rice.getInstance().getStep(0);
        CharSequence tips = null;

        if (step!=null) tips = step.topTips();


        String stepName = ProcessInfo_rice.getInstance().getStepName(0);
        buriedPointFalg = stepName;
        switch (buriedPointFalg){
            case "personal_info":
                activityFlag = "BASIC";
                if (TextUtils.isEmpty(tips)) tips = getText(R.string.process_tips_personal);
                break;
            case "work_info":
                activityFlag = "WORK";
                break;
            case "contact_info":
                activityFlag = "CONTACT";
                if (TextUtils.isEmpty(tips)) tips = getText(R.string.process_tips_contact);
                break;
            case "account_info":
                activityFlag = "BVN";
                break;
            default:
                activityFlag = buriedPointFalg;
        }

        if (TextUtils.isEmpty(tips)) tipsView.setVisibility(View.GONE);
        else {
            tipsTv.setText(tips);
            tipsView.setVisibility(View.VISIBLE);
        }

        if (step ==null) return;

        String title = ProcessInfo_rice.getInstance().getStepTitle();
        if (!TextUtils.isEmpty(title)) titleView.setTitle(title);
        else titleView.setTitle(StringUtil_rice.processTitleFormat(ProcessInfo_rice.getInstance().getStepName(0)));

        //联系人信息单独处理
        if (step.isContact()){

            for (int i = 0; i< step.getExtDataListSize(); i++){
                ProcessData_rice data = step.getExtProcessData(i);
                if (data==null) continue;
                addInputView(data,null);
            }

            int count = 0;

            while (count< step.getItemCount()){//联系人数量

                //添加标题
                View contactTitleView = LayoutInflater.from(this).inflate(R.layout.view_contact_title,null);
                TextView titleTv = contactTitleView.findViewById(R.id.vct_tv_title);
                if (count<1) titleTv.setText(getString(R.string.contact_title));
                else titleTv.setText(getString(R.string.contact_title_num,(count+1)));
                groupLayout.addView(contactTitleView);

                for (int i = 0; i< step.getDataListSize(); i++){
                    ProcessData_rice data = step.getProcessData(i);
                    if (data==null) continue;
                    addInputView(data, step.getRelationShips(count));

                }

                count++;
            }

            return;
        }

        for (int i = 0; i< step.getDataListSize(); i++){
            ProcessData_rice data = step.getProcessData(i);
            if (data==null) continue;
            addInputView(data,null);
        }
    }

    //添加信息输入控件
    @SuppressLint("InflateParams")
    private void addInputView(ProcessData_rice data, ArrayList<String> relationships){

        View inputView = null;

        switch (data.getAction()){

            case Constant_rice.Data_Action_Select:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_select_rice,null);
                SelectViewManager_rice selectViewManager = new SelectViewManager_rice(inputView,data,buriedPointFalg);
                infoInputViewManagers.add(selectViewManager);
                break;

            case Constant_rice.Data_Action_Date_Pick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_date_picker_rice,null);
                DatePickViewManager_rice datePickWidgetsManager = new DatePickViewManager_rice(inputView,data,buriedPointFalg);
                infoInputViewManagers.add(datePickWidgetsManager);
                break;

            case Constant_rice.Data_Action_Gender_Pick:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_gender_select_rice,null);
                GenderSelectViewManager_rice genderSelectViewManager = new GenderSelectViewManager_rice(inputView,data,buriedPointFalg);
                infoInputViewManagers.add(genderSelectViewManager);
                break;

            case Constant_rice.Data_Action_Credit_Report://尼日同意征信收集模块
                inputView = LayoutInflater.from(this).inflate(R.layout.view_credit_report_niri_rice,null);
                CreditReportViewManager_Niri_rice creditReportViewManager = new CreditReportViewManager_Niri_rice(inputView,data);
                infoInputViewManagers.add(creditReportViewManager);
                break;

            case Constant_rice.Data_Action_Bank_Pick://尼日银行选择模块
                bankNameData = data;
                HttpManager_rice.getInstance().fetchBankCodes_Niri();
                break;
                
            case Constant_rice.Data_Action_Relation://联系人-关系
                String others = getString(R.string.others);
                if (relationships!=null) data.setRelationships(relationships,others);
                inputView = LayoutInflater.from(this).inflate(R.layout.view_select_relationship,null);
                SelectRelationshipViewManager_rice contactSelectViewManager = new SelectRelationshipViewManager_rice(inputView,data,buriedPointFalg,others);
                addContactRelationWidget(contactSelectViewManager);
                break;

            case Constant_rice.Data_Action_Name://联系人-名字

                Intent intent = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);

                inputView = LayoutInflater.from(this).inflate(R.layout.view_contact_input_rice,null);
                final int num = contactWSList.size()-1;
                ContactViewManager_rice nameCsm = new ContactViewManager_rice(inputView,data,() -> {
                    try {
                        selectContact = num;
                        startTime = System.currentTimeMillis();
                        selectContactArl.launch(intent);
                    }catch (Exception e){
                        StringUtil_rice.printException(e);
                    }
                },buriedPointFalg,intent.resolveActivity(getPackageManager()) != null);
                addContactNameWidget(nameCsm);

                if (inputView!=null) groupLayout.addView(inputView,groupLayout.getChildCount()-1);
                return;

            case Constant_rice.Data_Action_Phone://联系人-电话

                Intent intent2 = new Intent(Intent.ACTION_PICK, ContactsContract.CommonDataKinds.Phone.CONTENT_URI);

                inputView = LayoutInflater.from(this).inflate(R.layout.view_contact_input_rice,null);
                final int num1 = contactWSList.size()-1;
                ContactViewManager_rice mobileCsm = new ContactViewManager_rice(inputView,data,() -> {
                    try {
                        selectContact = num1;
                        startTime = System.currentTimeMillis();
                        selectContactArl.launch(intent2);
                    }catch (Exception e){
                        StringUtil_rice.printException(e);
                    }
                },buriedPointFalg,intent2.resolveActivity(getPackageManager()) != null);
                addContactMobileWidget(mobileCsm);

                if (inputView!=null) groupLayout.addView(inputView,groupLayout.getChildCount()-1);
                return;

            case Constant_rice.Data_Action_Input:
            default:
                inputView = LayoutInflater.from(this).inflate(R.layout.view_input_rice,null);
                InputViewManager_rice inputWidgetsManager = new InputViewManager_rice(inputView,data,buriedPointFalg);
                infoInputViewManagers.add(inputWidgetsManager);
                break;
        }

        if (inputView!=null) groupLayout.addView(inputView);
    }

    @Override
    public void recordPageResumeEvent_rice() {
        HttpManager_rice.getInstance().saveUserBuriedPoint((buriedPointFalg + "_START").toUpperCase());
    }

    @Override
    public void recordPagePauseEvent_rice() {
        HttpManager_rice.getInstance().saveUserBuriedPoint((buriedPointFalg + "_END").toUpperCase());
    }

    private void addContactRelationWidget(SelectRelationshipViewManager_rice selectViewManager_peamongy){
        if (contactWSList.isEmpty() || contactWSList.get(contactWSList.size()-1).relationW!=null){
            contactWSList.add(new ContactInputWigets());
        }
        contactWSList.get(contactWSList.size()-1).relationW = selectViewManager_peamongy;
    }

    private void addContactMobileWidget(ContactViewManager_rice contactSelectViewManager){
        if (contactWSList.isEmpty() || contactWSList.get(contactWSList.size()-1).mobileW!=null){
            contactWSList.add(new ContactInputWigets());
        }
        contactWSList.get(contactWSList.size()-1).mobileW = contactSelectViewManager;
    }

    private void addContactNameWidget(ContactViewManager_rice contactSelectViewManager){
        if (contactWSList.isEmpty() || contactWSList.get(contactWSList.size()-1).nameW!=null){
            contactWSList.add(new ContactInputWigets());
        }
        contactWSList.get(contactWSList.size()-1).nameW = contactSelectViewManager;
    }

}